package com.lyl.excel.valid;

import cn.hutool.core.collection.CollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;
import java.util.function.Consumer;

/**
 * @author Mr.Luo
 * @date 2022-09-27 17:12
 * @desc
 */
@Component
@SuppressWarnings("all")
public class ExcelUtil {
    private static Validator VALIDATOR;
    @Autowired
    private Validator validator;

    @PostConstruct
    private void init() {
        VALIDATOR = validator;
    }

    public static <T extends ExcelError> boolean valid(T t, ExcelResult<T> result, Class<?>... groups) {
        Set<ConstraintViolation<T>> error = VALIDATOR.validate(t, groups);
        boolean empty = error.isEmpty();
        if (!empty) {
            ConstraintViolation<T> first = CollUtil.getFirst(error);
            result.addUnReplaceCount();
            t.setError(first.getMessage());
            result.addErrorData(t);
        } else {
            result.addReplaceCount();
        }
        return empty;
    }

    public static <T> boolean valid(T t, Consumer<Set<ConstraintViolation<T>>> failConsumer, Class<?>... groups) {
        Set<ConstraintViolation<T>> errors = VALIDATOR.validate(t, groups);
        boolean valid = errors.isEmpty();
        if (!valid) {
            failConsumer.accept(errors);
        }
        return valid;
    }

    public static <T> boolean valid(T t, Class<?>... groups) {
        return VALIDATOR.validate(t, groups).isEmpty();
    }
}
